package com.example.by.mdb.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.by.mdb.R;
import com.example.by.mdb.activity.App;
import com.example.by.mdb.activity.DianJian;
import com.example.by.mdb.activity.InspectionActivity;
import com.example.by.mdb.db.MyDatabaseHelper;
import com.example.by.mdb.util.Util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import static com.example.by.mdb.R.id.layout;

/**
 * Created by BY on 2016/1/5.
 */
public class SpotInspectionFragment extends Fragment {
    private View view;
    private TextView docVersion;
    private ListView myTaskListView;
    private ArrayList<String> id, name, totalCount, fileNames, eqps, numbers, eqpList;
    private List completedCount;
    private SQLiteDatabase db;
    private MyTaskAdapter myTaskAdapter;
    private Button exportButton;
    private int index = 0;
    private App app;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.my_task_fragment, null);
        init();
        initData();
        myTaskAdapter = new MyTaskAdapter();
        myTaskListView.setAdapter(myTaskAdapter);
        getEqpList();//读取设备列表
        readEqp();//读取设备信息
        return view;
    }

    private void refresh() {
        id.clear();
        name.clear();
        totalCount.clear();
        completedCount.clear();
        System.out.println("refresh");
        initData();//初始化数据


        myTaskListView.setAdapter(myTaskAdapter);
    }

    @Override
    public void onResume() {
        refresh();
        index++;
        Date date = new Date();
        System.out.println(date.getTime());
        if (index > 1) {
            String name = "result_maintain.txt";
            final File file = new File(Environment.getExternalStorageDirectory(), name);
            outPutFile(file, "result_maintain", Util.fileName("table_ioc"));
        }

        super.onResume();
    }


    private void initData() {
        System.out.println("initData");


//        if (tableNames.size() > 0) {
        Cursor cursor = db.query("pda_maintain", new String[]{"eqpno"}, "file_name=? and groupno = ?", new String[]{Util.fileName("table_ioc"), app.getGroupNo()}, null, null, null);
        if (cursor.moveToFirst()) {
//            name.add(cursor.getString(cursor.getColumnIndex("eqpno")));
            for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
                String equName = cursor.getString(cursor.getColumnIndex("eqpno"));
                if (!name.contains(equName)) {
                    name.add(equName);
                    Cursor count = db.query("pda_maintain", new String[]{"eqpno"}, "eqpno=? and file_name=? and groupno = ?", new String[]{equName, Util.fileName("table_ioc"), app.getGroupNo()}, null, null, null);
                    totalCount.add(count.getCount() + "");
                    Cursor count1 = db.query("pda_maintain", new String[]{"flag"}, "eqpno=? and flag=? and file_name=? and groupno = ?", new String[]{equName, "1", Util.fileName("table_ioc"), app.getGroupNo()}, null, null, null);
                    completedCount.add(count1.getCount());
                    id.add(id.size() + 1 + "");
                    count.close();
                    count1.close();
                }
            }
        } else {
            File file = new File(Environment.getExternalStorageDirectory(), "result_maintain.txt");
            BufferedWriter bw = null;
            try {
                bw = new BufferedWriter(new FileWriter(file));
                bw.append("");
                bw.flush();
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        for (int i = 0; i < totalCount.size(); i++) {
            if ((totalCount.get(i) + "").equals(completedCount.get(i) + "")) {
                name.add(name.get(i));
                totalCount.add(totalCount.get(i));
                completedCount.add(completedCount.get(i));
                name.remove(i);
                totalCount.remove(i);
                completedCount.remove(i);
            }
        }
        cursor.close();
    }

//    }

    private void init() {
        app = (App) getActivity().getApplication();
        MyDatabaseHelper myDatabaseHelper = new MyDatabaseHelper(getContext(), "pda.db");
        db = myDatabaseHelper.getReadableDatabase();
        id = new ArrayList<>();
        name = new ArrayList<>();
        totalCount = new ArrayList<>();
        completedCount = new ArrayList<>();
        fileNames = new ArrayList<>();
        eqps = new ArrayList<>();
        numbers = new ArrayList<>();
        eqpList = new ArrayList<>();
//        tableNames = new ArrayList<String>();
        LinearLayout eqpLinearLayout = (LinearLayout) view.findViewById(R.id.eqpLinearLayout);
        eqpLinearLayout.setBackgroundColor(Color.parseColor("#79cff7"));
        docVersion = (TextView) view.findViewById(R.id.docVersion);
        docVersion.setText("文档版本: IOC（HH）-W-8001-4");
        myTaskListView = (ListView) view.findViewById(R.id.mytaskListView);
        exportButton = (Button) view.findViewById(R.id.exportButton);
        exportButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final AlertDialog dialog = new AlertDialog.Builder(getContext()).create();
                final LayoutInflater inflater = LayoutInflater.from(getContext());
                View view = inflater.inflate(R.layout.eqp_list, null);
                ListView listView = (ListView) view.findViewById(R.id.eqpListView);
                listView.setAdapter(new BaseAdapter() {
                    @Override
                    public int getCount() {
                        return eqps.size();
                    }

                    @Override
                    public Object getItem(int position) {
                        return eqps.get(position);
                    }

                    @Override
                    public long getItemId(int position) {
                        return position;
                    }

                    @Override
                    public View getView(int position, View convertView, ViewGroup parent) {
                        View view1 = inflater.inflate(R.layout.eqp_list_item, null);
                        TextView textView = (TextView) view1.findViewById(R.id.eqpTextView);
                        textView.setText(eqps.get(position));
                        return view1;
                    }
                });
                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        importEqp(position);//导入选中设备数据
                        dialog.dismiss();
                        refresh();
                    }
                });
                dialog.setView(view);
                dialog.show();
            }
        });

    }

    private void importEqp(int position) {
        File path = Environment.getExternalStorageDirectory();
        File[] files = path.listFiles();
        fileNames = getFileName(files);
        for (Object fileName : fileNames) {
            String name = fileName + ".txt";
            File file = new File(Environment.getExternalStorageDirectory(), name);
            if (name.contains(Util.fileName("table_ioc"))) {
                BufferedReader br = null;
                try {
                    br = new BufferedReader(new FileReader(file));
                    String line = "";
                    while ((line = br.readLine()) != null) {
                        String[] s = line.split(App.DIVIDE);
                        String[] s1 = Arrays.copyOf(s, s.length + 1);
                        s1[s.length] = (String) fileName;
                        s1[0] = eqps.get(position);
                        if (s[0].equals(numbers.get(position))) {
                            Cursor cursor = db.query("pda_maintain", new String[]{"eqpno"}, "eqpno=? and checkno=? and file_name=?", new String[]{eqps.get(position), s[2], (String) fileName}, null, null, null);
                            if (!cursor.moveToFirst()) {
                                String sql = "insert into pda_maintain(eqpno,edition,checkno,rank,groupno,checkitem1,checkitem2,checkitem3,item,standard1,standard2,unit,type,frequency,notice,file_name) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
                                db.execSQL(sql, s1);
                                System.out.println(line.toString());
                            }
                            cursor.close();
                        }
                    }
                    br.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void getEqpList() {
        App app = (App) getActivity().getApplication();
        String groupNo = app.getGroupNo();
        File file = new File(Environment.getExternalStorageDirectory(), "eqpName_server.txt");
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(file));
            String line = "";
            while ((line = br.readLine()) != null) {
                String[] s = line.split(App.DIVIDE);
                if (s[2].equals(groupNo)) {
                    eqpList.add(s[0]);
                }
            }
            System.out.println("eqplist size:" + eqpList.size());
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void readEqp() {
        File path = Environment.getExternalStorageDirectory();
        File[] files = path.listFiles();
        fileNames = getFileName(files);
        for (Object fileName : fileNames) {
            String name = fileName + ".txt";
            File file = new File(Environment.getExternalStorageDirectory(), name);
            if (name.contains(Util.fileName("Link"))) {
                BufferedReader br = null;
                try {
                    br = new BufferedReader(new FileReader(file));
                    String line = "";
                    while ((line = br.readLine()) != null) {
                        String[] s = line.split(App.DIVIDE);
                        if (eqpList.contains(s[1]) && s[3].startsWith("999")) {
                            numbers.add(s[0]);
                            eqps.add(s[1]);
                        }
                    }
                    TreeMap<String, String> map = new TreeMap<>();
                    for (int i = 0; i < eqps.size(); i++) {
                        map.put(eqps.get(i), numbers.get(i));
                    }
                    Collections.sort(eqps);
                    numbers.clear();
                    for (int i = 0; i < eqps.size(); i++) {
                        numbers.add(map.get(eqps.get(i)));
                    }
//                    System.out.println(map);
                    br.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


    private ArrayList getFileName(File[] files) {
        ArrayList fileNames = new ArrayList();
        if (files != null) {
//                name = new ArrayList();
            for (File file : files) {
                String fileName = file.getName();
                if (fileName.startsWith("Link") || fileName.startsWith("table_ioc")) {
                    System.out.println(fileName);
                    String[] name = fileName.split("\\.");
//                        System.out.println(name[0]);
                    fileNames.add(name[0]);
                }
            }
        }
        return fileNames;
    }

    private void outPutFile(File file, String table, String fileName) {
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new FileWriter(file));
            Cursor cursor = db.query(table, null, "file_name=? and empno =?", new String[]{fileName, app.getEmpno()}, null, null, null);
            if (cursor.moveToFirst()) {
                System.out.println("output");
                String[] cursorNames = cursor.getColumnNames();
                for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
                    for (int i = 1; i < cursorNames.length - 1; i++) {
                        if (i == cursorNames.length - 2) {
                            if (cursor.getString(cursor.getColumnIndex(cursorNames[i])).equals("")) {
                                bw.append("null");
                            } else {
                                bw.append(cursor.getString(cursor.getColumnIndex(cursorNames[i])));
                            }
                        } else {
                            if (cursor.getString(cursor.getColumnIndex(cursorNames[i])).equals("")) {
                                bw.append("null<-->");
                            } else {
                                bw.append(cursor.getString(cursor.getColumnIndex(cursorNames[i])) + "<-->");
                            }
                        }
                    }
                    bw.newLine();
                }
            }
            cursor.close();
            bw.flush();
            bw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class MyTaskAdapter extends BaseAdapter {
        LayoutInflater inflater = LayoutInflater.from(getContext());
        Intent intent = new Intent(getContext(), DianJian.class);

        @Override
        public int getCount() {
            return id.size();
        }

        @Override
        public Object getItem(int position) {
            return id.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder = null;
            if (null == convertView) {
                viewHolder = new ViewHolder();
                convertView = inflater.inflate(R.layout.list_item2, null);
                viewHolder.layout = (LinearLayout) convertView.findViewById(layout);
                viewHolder.id = (TextView) convertView.findViewById(R.id.id);
                viewHolder.name = (TextView) convertView.findViewById(R.id.name);
                viewHolder.totalCount = (TextView) convertView.findViewById(R.id.totalCount);
                viewHolder.compeletedCount = (TextView) convertView.findViewById(R.id.compeletedCount);
                viewHolder.startInspection = (Button) convertView.findViewById(R.id.startInspection);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            viewHolder.id.setText((CharSequence) id.get(position));
            viewHolder.name.setText((CharSequence) name.get(position));
            viewHolder.totalCount.setText((CharSequence) totalCount.get(position));
            viewHolder.compeletedCount.setText(String.valueOf(completedCount.get(position)));
            if ((totalCount.get(position) + "").equals(completedCount.get(position) + "")) {
                viewHolder.startInspection.setText("点检完成");
                viewHolder.layout.setBackgroundColor(Color.GREEN);
            } else if (!String.valueOf(completedCount.get(position)).equals("0")) {
                viewHolder.startInspection.setText("继续点检");
            }
            viewHolder.startInspection.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bundle bundle = new Bundle();
                    bundle.putStringArrayList("eqpno", name);
                    bundle.putInt("index", position);
                    bundle.putString("name", name.get(position));
                    bundle.putString("table", "pda_maintain");
                    bundle.putString("fileName", Util.fileName("table_ioc"));
                    intent.putExtra("eqpno", bundle);
                    startActivity(intent);
                }
            });
            convertView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    AlertDialog.Builder alert = new AlertDialog.Builder(getContext());
                    alert.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            deleteItem(position);
                        }
                    });
                    alert.setMessage("删除该项？");
                    alert.setNegativeButton("取消", null);
                    alert.show();
                    return true;
                }
            });
            return convertView;
        }

        private class ViewHolder {
            TextView id;
            TextView name;
            TextView totalCount;
            TextView compeletedCount;
            Button startInspection;
            LinearLayout layout;
        }
    }

    private void deleteItem(int position) {
//        System.out.println(Util.fileName("table_ioc")+"   "+name.get(position));
//        Cursor count = db.query("pda_maintain", new String[]{"eqpno"}, "eqpno=? and file_name=?", new String[]{name.get(position), Util.fileName("table_ioc")}, null, null, null);
//        System.out.println(count.getCount());
//        count.close();
        db.delete("pda_maintain", "file_name=? and eqpno=?", new String[]{Util.fileName("table_ioc"), name.get(position)});
        refresh();
    }

}